import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'bean/city_response_bean.dart';

class CityWidget extends StatefulWidget {
  final String selectedName;
  final String cityType;

  const CityWidget({Key key, this.selectedName, this.cityType = "04"})
      : super(key: key);

  @override
  _CityWidgetState createState() => _CityWidgetState();

  ///跳转方法
  static Future<EditTextAndValue> navigatorPush(
      BuildContext context, String selectedId) {
    return RouterUtils.routeForFutureResult<EditTextAndValue>(
      context,
      CityWidget(
        selectedName: selectedId,
      ),
    );
  }
}

class _CityWidgetState extends State<CityWidget> {
  bool isLightUp = false; //确认按钮是否亮起
  String mCityText; //项目文本
  String selectedName; //选中的行ID

  CommonListPageWidgetState<CityListItemBean, CityResponseBean> _mState;

  void setCommonListState(
      CommonListPageWidgetState<CityListItemBean, CityResponseBean> state) {
    _mState = state;
  }

  @override
  //初始化
  void initState() {
    // TODO: implement initState
    super.initState();
    selectedName = widget.selectedName;
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
       Scaffold(
        // resizeToAvoidBottomInset: false,
        // resizeToAvoidBottomPadding: false,
        backgroundColor: Color(0xFF191E31),
        body: CommonPackUpKeyboardWidget(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              _toTopBarWidget(),
              _searchDepartmentWidget(),
              //下划线
              Container(
                height: 1,
                padding: const EdgeInsets.only(left: 21,),
                child: Divider(
                  height: 1.0,
                  indent: 0.0,
                  color: Color(0xFF303546),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              Expanded(
                child: _toCustomListWidget(),
              ),
            ],
          ),
        ),
      ),
      navigationBarColor: Color(0xFF191E31),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "城市",
      rightWidget: _buttonWidget(),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: isLightUp,
        width: 48,
        height: 24,
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 12,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          //提交按钮
          if (isLightUp) {
            _selectCity();
          }
        },
      ),
    );
  }

  void _selectCity() {
    if (mCityText == null || mCityText.isEmpty) {
      VgToastUtils.toast(context, "请输入城市名称");
      return;
    }
    List<CityListItemBean> cityList = _mState?.data;
    if (cityList == null || cityList.isEmpty) {
      RouterUtils.pop(context,
          result: EditTextAndValue(value: "", editText: mCityText));
      return;
    }
    for (CityListItemBean item in cityList) {
      if (item?.name == mCityText) {
        RouterUtils.pop(context,
            result: EditTextAndValue(value: item.id, editText: mCityText));
        return;
      }else {
        RouterUtils.pop(context,
            result: EditTextAndValue(value: "", editText: mCityText));
        return;
      }
    }
  }

  Widget _searchDepartmentWidget() {
    return Container(
      height: 50,
      color: Color(0xFF3A3F50),
      child: CommonEditCallbackWidget(
        hintText: "请输入城市名称",
        onChanged: (String cityText) {
          mCityText = cityText;
          if (cityText == null || cityText == "")
            isLightUp = false;
          else
            isLightUp = true;
          setState(() {});
        },
        onSubmitted: (String cityText) {
          mCityText = cityText;
          if (cityText == null || cityText == "")
            isLightUp = false;
          else
            isLightUp = true;
          setState(() {});
        },
      ),
    );
  }

  //封装的列表
  Widget _toCustomListWidget() {
    return CommonListPageWidget<CityListItemBean, CityResponseBean>(
      enablePullUp: false,
      enablePullDown: false,
      queryMapFunc:(int page) => {
        "authId": UserRepository.getInstance().authId ?? "",
        "name":"",
        "type": widget.cityType,
      },
      parseDataFunc: (VgHttpResponse resp) {
        CityResponseBean bean = CityResponseBean.fromMap(resp?.data);
        bean?.data?.removeWhere((element) => element == null || StringUtils.isEmpty(element.id) || StringUtils.isEmpty(element.name));
        return bean;
      },
      itemBuilder:
          (BuildContext context, int index, CityListItemBean itemBean) {
        return _toListItemWidget(context, index, itemBean);
      },
      //分割器构造器
      separatorBuilder: (context, int index, _) {
        return Container(
          height: 0.5,
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          padding: const EdgeInsets.only(left: 15),
          child: Container(
            color: Color(0xFF303546),
          ),
        );
        // return divider;
      },
      netUrl:ServerApi.BASE_URL + "app/appChooseInfo",
      httpType: VgHttpType.post,
      stateFunc: (CommonListPageWidgetState<CityListItemBean, CityResponseBean>
          state) {
        _mState = state;
      },
    );
  }

  Widget _toListItemWidget(
      BuildContext context, int index, CityListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        //判断字体是否选中
        selectedName = itemBean.id;
        setState(() {});
        //收键盘方法
        // FocusScope.of(context).requestFocus(FocusNode());
        VgToolUtils.removeAllFocus(context);
        //延迟执行
        Future.delayed(Duration(milliseconds: 10), () {
          RouterUtils.pop(context,
              result: EditTextAndValue(
                editText: itemBean.name,
                value: itemBean.id,
              ));
        });
      },
      child: Container(
        color: Color(0xFF21263C),
        height: 50,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Text(
          itemBean?.name ?? "",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: itemBean.id == selectedName
                ? Color(0xFF1890FF)
                : Color(0xFFD0E0F7),
            fontSize: 14,
          ),
        ),
      ),
    );
  }
}
